#!/bin/bash

REPO_URL="https://gitee.com/hypdream/SillyTavern.git"
BRANCH="release"
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m'

echo -e "${GREEN}这里是404号伪梦_(:з」∠)_${NC}"
echo -e "----------------------------"
echo -e "${GREEN}已配置全链路国内镜像加速，无需梯子${NC}"
echo -e "----------------------------"
echo -e "开始执行系统更新和软件安装..."

# 0. 更换Termux软件源为清华源
echo -e "${GREEN}【0/6】更换Termux软件源为国内镜像...${NC}"
TERMUX_PREFIX="/data/data/com.termux/files/usr"
APT_DIR="$TERMUX_PREFIX/etc/apt"

# 确保目录存在
mkdir -p "$APT_DIR/sources.list.d" || { echo -e "${RED}错误：无法创建sources.list.d目录${NC}"; exit 1; }

# 写入软件源配置
echo "deb https://mirrors.tuna.tsinghua.edu.cn/termux/apt/termux-main stable main" > "$APT_DIR/sources.list" || { echo -e "${RED}错误：无法写入主软件源${NC}"; exit 1; }
echo "deb https://mirrors.tuna.tsinghua.edu.cn/termux/apt/termux-science science stable" > "$APT_DIR/sources.list.d/science.list" || { echo -e "${RED}错误：无法写入science源${NC}"; exit 1; }
echo "deb https://mirrors.tuna.tsinghua.edu.cn/termux/apt/termux-games games stable" > "$APT_DIR/sources.list.d/game.list" || { echo -e "${RED}错误：无法写入game源${NC}"; exit 1; }

# 1. 执行pkg update（自动确认）
echo -e "${GREEN}【1/6】更新软件包列表...${NC}"
yes | pkg update || { echo -e "${RED}错误：pkg update 失败${NC}"; exit 1; }

# 2. 执行pkg upgrade（自动确认）
echo -e "${GREEN}【2/6】升级已安装的软件包...${NC}"
yes | pkg upgrade || { echo -e "${RED}错误：pkg upgrade 失败${NC}"; exit 1; }

# 3. 安装git（自动确认）
echo -e "${GREEN}【3/6】安装git...${NC}"
yes | pkg install git || { echo -e "${RED}错误：git安装失败${NC}"; exit 1; }

# 4. 安装nodejs（自动确认）并配置npm淘宝源
echo -e "${GREEN}【4/6】安装nodejs并配置npm源...${NC}"
yes | pkg install nodejs || { echo -e "${RED}错误：nodejs安装失败${NC}"; exit 1; }

# 设置npm淘宝源
npm config set registry https://registry.npmmirror.com

# 5. 克隆SillyTavern项目
echo -e "${GREEN}【5/6】克隆SillyTavern项目...${NC}"
command -v git >/dev/null 2>&1 || { echo -e "${RED}错误：未找到git命令，请手动安装${NC}"; exit 1; }

REPO_NAME=$(basename "$REPO_URL" .git)

# 克隆指定分支
git clone -b "$BRANCH" "$REPO_URL" || {
    echo -e "${RED}错误：仓库克隆失败，请检查网络连接${NC}"
    echo -e "尝试手动执行: git clone -b $BRANCH $REPO_URL"
    exit 1
}

# 6. 检查启动脚本并设置权限
echo -e "${GREEN}【6/6】检查启动脚本...${NC}"
START_SH_PATH="$REPO_NAME/start.sh"

if [ ! -f "$START_SH_PATH" ]; then
    echo -e "${RED}警告：未找到启动脚本 $START_SH_PATH${NC}"
else
    chmod +x "$START_SH_PATH" || echo -e "${YELLOW}警告：无法设置执行权限，请手动处理${NC}"
    
    # 将启动命令添加到.bashrc
    if grep -q "bash $START_SH_PATH" ~/.bashrc; then
        echo -e "${YELLOW}提示：已存在启动命令，跳过添加${NC}"
    else
        echo "# 自动添加：启动SillyTavern" >> ~/.bashrc
        echo "bash $(realpath "$START_SH_PATH")" >> ~/.bashrc
        echo -e "${GREEN}已将启动命令添加到 ~/.bashrc${NC}"
        echo -e "${GREEN}下次打开终端时将自动启动SillyTavern${NC}"
    fi
fi

# 完成提示
echo -e "----------------------------"
echo -e "${YELLOW}所有操作已完成₍^ >ω<^₎${NC}"
echo -e "${YELLOW}输入exit即可彻底退出终端${NC}"
echo -e "${YELLOW}感谢使用喵~${NC}"
echo -e "----------------------------"